package org.shj.hadoop.multiplemr;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

/**
 * 可以使用多个mapreduce来实现一个业务逻辑。如对多个文件进行统计，得到每个单词在每个文件中出现的
 * 次数。 此逻辑需要2个mapreduce实现
 * @author Administrator
 *
 */
public class IndexMR {
	
	public static class IndexMapper extends Mapper<LongWritable, Text, Text, Text>{

		private Text k = new Text();
		private Text v = new Text();
		
		@Override
		protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context)
				throws IOException, InterruptedException {
			String[] words = value.toString().split(" ");
			
			//此mapper是读文件，所以InputSplit的子类是FileSplit，可从FileSplit中得到文件名
			FileSplit inputSplit = (FileSplit)context.getInputSplit();
			String path = inputSplit.getPath().toString();
			
			for(String word : words){
				k.set(word + "->" + path);
				v.set("1");
				context.write(k, v);
			}
		}
		
	}
	
	public static class IndexCombiner extends Reducer<Text, Text, Text, Text>{

		private Text k = new Text();
		private Text v = new Text();
		
		@Override
		protected void reduce(Text key, Iterable<Text> values, Reducer<Text, Text, Text, Text>.Context context)
				throws IOException, InterruptedException {
			String[] wordAndPath = key.toString().split("->");
			String word = wordAndPath[0];
			String path = wordAndPath[1];
			int count = 0;
			for(Text t : values){
				count += Integer.parseInt(t.toString());
			}
			k.set(word);
			v.set(path + "->" + count);
			context.write(k, v);
		}
	}
	
	public static class IndexReducer extends Reducer<Text, Text, Text, Text>{

		@Override
		protected void reduce(Text key, Iterable<Text> values, Reducer<Text, Text, Text, Text>.Context context)
				throws IOException, InterruptedException {
			StringBuilder sb = new StringBuilder();
			for(Text t : values){
				sb.append(t.toString()).append("\t");
			}
			context.write(key, new Text(sb.toString()));
		}
	}

	public static void main(String[] args) throws Exception{
		Configuration conf = new Configuration();
		Job job = Job.getInstance(conf);
		
		job.setJarByClass(IndexMR.class);
		job.setMapperClass(IndexMapper.class);
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(Text.class);
		
		FileInputFormat.addInputPath(job, new Path(args[0]));
		
		job.setCombinerClass(IndexCombiner.class);
		job.setReducerClass(IndexReducer.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);
		
		FileOutputFormat.setOutputPath(job, new Path(args[1]));

		job.waitForCompletion(true);
	}

}
